package com.example.deom.controller;

import com.example.deom.common.AjaxResult;
import com.example.deom.common.ApplicationVariable;
import com.example.deom.common.PasswordTools;
import com.example.deom.common.UserSessionTools;
import com.example.deom.entity.UserInfo;
import com.example.deom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/reg")
    public AjaxResult reg(UserInfo userInfo){
        if(userInfo == null || !StringUtils.hasLength(userInfo.getUsername())
        || !StringUtils.hasLength(userInfo.getPassword()))
            return AjaxResult.fail(-1,"参数有误");
       userInfo.setPassword(userInfo.getPassword());
        int result = userService.reg(userInfo);
       return AjaxResult.success(result);
    }
    @RequestMapping("/login")
    public AjaxResult login(String username, String password, HttpServletRequest request){
        if (!StringUtils.hasLength(username)||
        !StringUtils.hasLength(password))
            return AjaxResult.fail(-1,"参数有误");
        UserInfo userInfo = userService.login(username);
        if(userInfo == null || userInfo.getId() <= 0){
            System.out.printf("用户名错误");
            return AjaxResult.fail(-2,"用户名或密码输入有误");
        }
        if(!password.equals(userInfo.getPassword())){
            System.out.printf("密码错误");
            return AjaxResult.fail(-2,"用户名或密码输入有误");
        }
        //将当前成功登录的用信息存储到session
        HttpSession session = request.getSession();
        session.setAttribute(ApplicationVariable.SESSION_KEY_USERINFO,userInfo);
        return AjaxResult.success(1);
    }
    @RequestMapping("/logout")
    public AjaxResult logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute(ApplicationVariable.SESSION_KEY_USERINFO);
        return AjaxResult.success(1);
    }

    @RequestMapping("/islogin")
    public AjaxResult isLogin(HttpServletRequest request){
        if(UserSessionTools.getLoginUser(request) == null){
            //未登录
            return AjaxResult.success(0);
        }
        return AjaxResult.success(1);
    }
}
